package com.css.zfzx.fwsjcj.modules.structure.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.components.attach.repository.entity.SysAttachmentEntity;
import com.css.bpm.platform.components.attach.service.SysAttachment;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.commen.util.EasyPoiExcelUtil;
import com.css.zfzx.fwsjcj.modules.analysis.vo.AnalysisQueryVo;
import com.css.zfzx.fwsjcj.modules.structure.entity.*;
import com.css.zfzx.fwsjcj.modules.structure.repository.FwHighStructureRepository;
import com.css.zfzx.fwsjcj.modules.structure.repository.FwStructureFormRepository;
import com.css.zfzx.fwsjcj.modules.structure.service.FwHighStructureService;
import com.css.zfzx.fwsjcj.modules.structure.service.FwStructureFormService;
import com.css.zfzx.fwsjcj.modules.structure.verify.BrickStructureCheck;
import com.css.zfzx.fwsjcj.modules.structure.verify.HighStructureCheck;
import com.css.zfzx.fwsjcj.modules.structure.vo.FwHighStructureVo;
import com.css.zfzx.fwsjcj.modules.structure.vo.StructureQueryVo;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author leon
 * @Title: FwHighStructureServiceImpl
 * @Description: 高层结构
 * @date 2020/6/3 17:34
 */
@Slf4j
@Service
public class FwHighStructureServiceImpl implements FwHighStructureService {
    @Autowired
    private FwHighStructureRepository highStructureRepository;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private FwStructureFormService structureFormService;

    @Autowired
    private FwStructureFormRepository fwStructureFormRepository;
    @Resource
    private SysAttachment sysAttachment;

    private volatile static HashMap<String, List> divisionMap;

    @Override
    public void save(FwHighStructureEntity fwHighStructureEntity) {
        String userId = PlatformSessionUtils.getUserId();
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        /**
         * 砖石结构子表设置默认值（子表保存）
         */
        fwHighStructureEntity.setId(UUIDGenerator.getUUID());
        // 数据收集人名称
        fwHighStructureEntity.setCollectUser(user.getUserName());
        // 存数据收集人ID
        fwHighStructureEntity.setCreateUser(userId);
        fwHighStructureEntity.setCreateTime(new Date());
        fwHighStructureEntity.setDelFlag(Constant.DEL_NO);
        highStructureRepository.save(fwHighStructureEntity);

        /**
         * 主表保存
         */
        FwStructureFormEntity structureFormEntity = new FwStructureFormEntity();
        // 保存子表ID
        structureFormEntity.setStructureId(fwHighStructureEntity.getId());
        // 保存子表类型
        structureFormEntity.setStructureType(Constant.HIGH_STRUCTURE);
        // 保存子表省、市
        structureFormEntity.setBelongtoProvince(fwHighStructureEntity.getBelongtoProvince());
        structureFormEntity.setBelongtoCity(fwHighStructureEntity.getBelongtoCity());
        structureFormEntity.setBelongtoArea(fwHighStructureEntity.getBelongtoArea());
        // 保存子表建筑名称
        structureFormEntity.setBuildingName(fwHighStructureEntity.getBuildingName());
        // 保存子表建筑类型
        structureFormEntity.setSiteType(fwHighStructureEntity.getSiteType());
        // 保存建筑编号
        structureFormEntity.setStructureNum(fwHighStructureEntity.getHighStructureNum());
        // 保存任务id和名称
        structureFormEntity.setTaskId(fwHighStructureEntity.getTaskId());
        structureFormEntity.setTaskName(fwHighStructureEntity.getTaskName());
        structureFormEntity.setBuildingArea(fwHighStructureEntity.getBuildingArea()==null?0.0:fwHighStructureEntity.getBuildingArea());
        structureFormEntity.setStatus(fwHighStructureEntity.getStatus());
        structureFormService.save(structureFormEntity);
    }

    @Override
    @Transactional
    public void update(FwHighStructureEntity fwHighStructureEntity) {
        if (StringUtils.isEmpty(fwHighStructureEntity.getId())) {
            throw new RuntimeException("修改ID不能为空");
        }
        // 获取当前用户信息
        String userId = PlatformSessionUtils.getUserId();
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        /**
         * 设置默认值
         */
        fwHighStructureEntity.setUpdateUser(user.getUserId());
        fwHighStructureEntity.setUpdateTime(new Date());
        // 将不为空的数据拷贝到旧数据中
        //FwHighStructureEntity oldTarge = this.findById(fwHighStructureEntity.getId());
        //  若审核状态为审核未通过改为未提交
//        if(Constant.SP_NOT.equals(oldTarge.getStatus())){
//            oldTarge.setStatus(Constant.NO_SUB);
//        }
        if(Constant.SP_NOT.equals(fwHighStructureEntity.getStatus())){
            fwHighStructureEntity.setStatus(Constant.NO_SUB);
            fwHighStructureEntity.setCheckOpinion("");
            fwHighStructureEntity.setCheckUser("");
        }
        //SpringUtil.copyPropertiesIgnoreEmpty(fwHighStructureEntity, oldTarge);
        // 实体中必须有ID
        highStructureRepository.save(fwHighStructureEntity);

        /**
         * 主表保存
         */
        FwStructureFormEntity sourceStructureFormEntity = structureFormService.findStructureForm(Constant.HIGH_STRUCTURE, fwHighStructureEntity.getId());
        //FwStructureFormEntity targetStructureFormEntity = sourceStructureFormEntity;
        // 保存子表省
        sourceStructureFormEntity.setBelongtoProvince(fwHighStructureEntity.getBelongtoProvince());
        // 保存子表市
        sourceStructureFormEntity.setBelongtoCity(fwHighStructureEntity.getBelongtoCity());
        // 保存子表区县
        sourceStructureFormEntity.setBelongtoArea(fwHighStructureEntity.getBelongtoArea());
        // 保存子表建筑名称
        sourceStructureFormEntity.setBuildingName(fwHighStructureEntity.getBuildingName());
        // 保存子表建筑类型
        sourceStructureFormEntity.setSiteType(fwHighStructureEntity.getSiteType());
        // 若审核状态为审核未通过改为未提交
        if (Constant.SP_NOT.equals(sourceStructureFormEntity.getStatus())){
            sourceStructureFormEntity.setStatus(Constant.NO_SUB);
            sourceStructureFormEntity.setCheckOpinion("");
            sourceStructureFormEntity.setCheckUser("");
        }
        sourceStructureFormEntity.setStatus(fwHighStructureEntity.getStatus());
        sourceStructureFormEntity.setBuildingArea(fwHighStructureEntity.getBuildingArea()==null?0.0:fwHighStructureEntity.getBuildingArea());
        structureFormService.update(sourceStructureFormEntity);
    }

    @Override
    public JSONObject getPage(StructureQueryVo structureQueryVo, int curPage, int pageSize) {
        QFwHighStructureEntity q = QFwHighStructureEntity.fwHighStructureEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());

        // 查询条件
        if (structureQueryVo != null) {
            String buildingName = structureQueryVo.getBuildingName();
            predicate = ("".equals(buildingName) || buildingName == null) ? predicate : ExpressionUtils.and(predicate, q.buildingName.like("%" + buildingName + "%"));

            String belongtoProvince = structureQueryVo.getBelongtoProvince();
            predicate = ("".equals(belongtoProvince) || belongtoProvince == null) ? predicate : ExpressionUtils.and(predicate, q.belongtoProvince.like("%" + belongtoProvince + "%"));

            String belongtoCity = structureQueryVo.getBelongtoCity();
            predicate = ("".equals(belongtoCity) || belongtoCity == null) ? predicate : ExpressionUtils.and(predicate, q.belongtoCity.like("%" + belongtoCity + "%"));

            String siteType = structureQueryVo.getSiteType();
            predicate = ("".equals(siteType) || siteType == null) ? predicate : ExpressionUtils.and(predicate, q.siteType.like("%" + siteType + "%"));

            String status = structureQueryVo.getStatus();
            predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, q.status.eq(status));

        }
        // 删除标识
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.DEL_NO));

        QueryResults<FwHighStructureEntity> page = jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .offset(curPage - 1)   //起始页
                .limit(pageSize)  //每页大小
                .fetchResults();
        /**
         * 适配base转为JSONObject类型
         */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", page.getResults());
        jsonObject.put("total", page.getTotal());
        return jsonObject;
    }

    @Override
    public void delete(String id) {
        FwHighStructureEntity highStructureEntity = highStructureRepository.findById(id).get();
        highStructureEntity.setDelFlag(Constant.DEL_YES);
        update(highStructureEntity);
    }

    @Override
    public FwHighStructureEntity findById(String id) {
        return highStructureRepository.findById(id).get();
    }

    @Override
    public List<FwHighStructureEntity> findAll() {
        return highStructureRepository.findAll();
    }

    @Override
    public void submit(List<String> idList) {
        QFwHighStructureEntity q = QFwHighStructureEntity.fwHighStructureEntity;
        jpaQueryFactory.update(q)
                .set(q.status, Constant.DAI_SP)
                .where(q.id.in(idList))
                .execute();

    }
    public HashMap<String, List> divisionMap() {
        HashMap<String, List> map = new HashMap<>();
        // 所有省
        List<DivisionEntity> provinceDivisions = PlatformAPI.getDivisionAPI().getSubDivisions("root");
        for (DivisionEntity province : provinceDivisions) {
            String provinceName = province.getDivisionName();
            // 市
            List<DivisionEntity> cities = PlatformAPI.getDivisionAPI().getSubDivisions(province.getDivisionId());
            ArrayList<String> cityNames = new ArrayList<>();
            for (DivisionEntity city : cities) {
                String cityName = city.getDivisionName();
                cityNames.add(cityName);
                // 不为直辖市
                if (!"北京市".equals(provinceName) && !"天津市".equals(provinceName) && !"上海市".equals(provinceName) && !"重庆市".equals(provinceName)) {
                    // 获取市下面的区县
                    List<DivisionEntity> areas = PlatformAPI.getDivisionAPI().getSubDivisions(city.getDivisionId());
                    ArrayList<String> areaNames = new ArrayList<>();
                    for (DivisionEntity area : areas) {
                        String areaName = area.getDivisionName();
                        areaNames.add(areaName);
                    }
                    map.put(cityName, areaNames);
                }
            }
            // 省对应下面的市(直辖市-对应的是区)
            map.put(provinceName, cityNames);
        }
        return map;
    }
    @Override
    public String exportExcel(String taskName, String taskId, MultipartFile file, HttpServletResponse response) {
        // 单例初始化省市区map
        if (divisionMap == null) {
            synchronized (this) {
                if (divisionMap == null) {
                    divisionMap = divisionMap();
                }
            }
        }
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(new HighStructureCheck(divisionMap));
            // 获取到Excel数据
            ExcelImportResult<FwHighStructureVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FwHighStructureVo.class, params);
            List<FwHighStructureVo> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            // 重复后失败条数
            int failCount = saveFwHighStructure(taskName, taskId, list, sb);
            if (failCount > 0) {
                // result.getFailList().size()为保存时出错的条数
                int failList = firstList + result.getFailList().size() - list.size();
                returnMsg.append("成功导入" + (result.getList().size() - failCount) + "条，失败" + (failList + failCount) + "条<br/>");
                returnMsg.append("样本编码" + failCount + "存在重复数据<br/>");
                returnMsg.append(sb);
            } else {
                returnMsg.append("成功导入" + (result.getList().size() - failCount) + "条，失败" + (result.getFailList().size() + failCount) + "条<br/>");
                returnMsg.append(sb);
            }
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FwHighStructureVo> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FwHighStructureVo highStructureVo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + highStructureVo.getRowNum() + "行" + highStructureVo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Transactional
    @Override
    public void updateFileId(String formId, String fileId) {
        FwHighStructureEntity fwHighStructureEntity = findById(formId);

        if (!StringUtils.isEmpty(fwHighStructureEntity)) {
            highStructureRepository.updateFile(formId, fileId);

        }
    }


    public int saveFwHighStructure(String taskName, String taskId, List<FwHighStructureVo> list, StringBuilder message) {
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            FwHighStructureEntity highStructureEntity = new FwHighStructureEntity();
            FwHighStructureVo highStructureVo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(highStructureVo, highStructureEntity);
            String delFlag="0";
            // 根据样本编号判断重复导入性
            FwHighStructureEntity byHighStructureNum = highStructureRepository.findByHighStructureNumAndDelFlag(highStructureVo.getHighStructureNum(),delFlag);
            if (!StringUtils.isEmpty(byHighStructureNum)) {
                message.append("样本编码" + highStructureVo.getHighStructureNum() + "已重复");
                ++count;
            } else {
                highStructureEntity.setTaskId(taskId);
                highStructureEntity.setTaskName(taskName);
                save(highStructureEntity);
            }
        }
        return count;
    }

    @Override
    public long count(AnalysisQueryVo analysisQueryVo) {
        // 查询条件
        Specification querySpecification = new Specification<FwHighStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwHighStructureEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(analysisQueryVo)) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    //抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }
                    //柱混凝土强度等级
                    String zhntqdLevel = analysisQueryVo.getZhntqdLevel();
                    if (!StringUtils.isEmpty(zhntqdLevel)) {
                        predicates.add(criteriaBuilder.equal(root.get("colConcreteStrengthGrade"), zhntqdLevel));
                    }
                   /* //主要柱截面尺寸
                    String zyzjmSize = analysisQueryVo.getZyzjmSize();
                    if (!StringUtils.isEmpty(zyzjmSize)) {
                        //主要柱截面尺寸<=300
                        if (Constant.ZYZJM_SIZE_LESS_300.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.le(root.get("mainColSectionSize"), 300));
                        }
                        //主要截面尺寸300-400
                        if (Constant.ZYZJM_SIZE_BETWEEN_300_400.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.between(root.get("mainColSectionSize"), 300, 400));
                        }
                        //主要截面尺寸400-600
                        if (Constant.ZYZJM_SIZE_BETWEEN_400_600.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.between(root.get("mainColSectionSize"), 400, 600));
                        }
                        //主要截面尺寸>=600
                        if (Constant.ZYZJM_SIZE_MORE_600.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.ge(root.get("mainColSectionSize"), 600));
                        }
                    }*/
                    //最大柱间距
                    String zdzSpan = analysisQueryVo.getZdzSpan();
                    if (!StringUtils.isEmpty(zdzSpan)) {
                        //最大柱间距<=5
                        if (Constant.ZDZ_SPAN_LESS_5.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.le(root.get("maxColSpace"), 5));
                        }
                        //最大柱间距5-8
                        if (Constant.ZDZ_SPAN_BETWEEN_5_8.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxColSpace"), 5, 8));
                        }
                        //最大柱间距8-10
                        if (Constant.ZDZ_SPAN_BETWEEN_8_10.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxColSpace"), 8, 10));
                        }
                        //最大柱间距>=10
                        if (Constant.ZDZ_SPAN_MORE_10.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.ge(root.get("maxColSpace"), 10));
                        }
                    }
                    //剪力墙混凝土强度等级
                    String jlqhntqdLevel = analysisQueryVo.getJlqhntqdLevel();
                    if (!StringUtils.isEmpty(jlqhntqdLevel)) {
                        predicates.add(criteriaBuilder.equal(root.get("shearwellConcreteStrengthGrade"), jlqhntqdLevel));
                    }
                    //剪力墙最大间距
                    String jlqzdSpan = analysisQueryVo.getJlqzdSpan();
                    if (!StringUtils.isEmpty(jlqzdSpan)) {
                        //剪力墙最大间距<=30m
                        if (Constant.JLQZD_SPAN_LESS_30.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.le(root.get("maxShearwellSpace"), 30));
                        }
                        //剪力墙最大间距30-40m
                        if (Constant.JLQZD_SPAN_BETWEEN_30_40.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxShearwellSpace"), 30, 40));
                        }
                        //剪力墙最大间距40-50m
                        if (Constant.JLQZD_SPAN_BETWEEN_40_50.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxShearwellSpace"), 40, 50));
                        }
                        //剪力墙最大间距50-60m
                        if (Constant.JLQZD_SPAN_BETWEEN_50_60.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxShearwellSpace"), 50, 60));
                        }
                        //剪力墙最大间距>=60m
                        if (Constant.JLQZD_SPAN_MORE_60.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.ge(root.get("maxShearwellSpace"), 60));
                        }
                    }
                    //剪力墙厚度
                    String shearwellThickness = analysisQueryVo.getShearwellThickness();
                    if (!StringUtils.isEmpty(shearwellThickness)) {
                        //剪力墙厚度<=160mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_LESS_160.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.le(root.get("shearwellThickness"), 160));
                        }
                        //剪力墙厚度160mm-200mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_BETWEEN_160_200.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.between(root.get("shearwellThickness"), 160, 200));
                        }
                        //剪力墙厚度200mm-400mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_BETWEEN_200_400.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.between(root.get("shearwellThickness"), 200, 400));
                        }
                        //剪力墙厚度400mm-700mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_BETWEEN_400_700.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.between(root.get("shearwellThickness"), 400, 700));
                        }
                        //剪力墙厚度>=700mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_MORE_700.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.ge(root.get("shearwellThickness"), 700));
                        }
                    }
                    //屋盖类别
                    String roofType = analysisQueryVo.getRoofType();
                    if (!StringUtils.isEmpty(roofType)) {
                        predicates.add(criteriaBuilder.equal(root.get("roofType"), roofType));
                    }
                    //楼盖类别
                    String floorType = analysisQueryVo.getFloorType();
                    if (!StringUtils.isEmpty(floorType)) {
                        predicates.add(criteriaBuilder.equal(root.get("floorType"), floorType));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.IS_VALID_YES));
                //审核通过的
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
            }
        };
        return highStructureRepository.count(querySpecification);
    }

    @Override
    public double area(AnalysisQueryVo analysisQueryVo) {
        // 查询条件
        Specification querySpecification = new Specification<FwHighStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwHighStructureEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(analysisQueryVo)) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    //抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }
                    //柱混凝土强度等级
                    String zhntqdLevel = analysisQueryVo.getZhntqdLevel();
                    if (!StringUtils.isEmpty(zhntqdLevel)) {
                        predicates.add(criteriaBuilder.equal(root.get("colConcreteStrengthGrade"), zhntqdLevel));
                    }
                   /* //主要柱截面尺寸
                    String zyzjmSize = analysisQueryVo.getZyzjmSize();
                    if (!StringUtils.isEmpty(zyzjmSize)) {
                        //主要柱截面尺寸<=300
                        if (Constant.ZYZJM_SIZE_LESS_300.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.le(root.get("mainColSectionSize"), 300));
                        }
                        //主要截面尺寸300-400
                        if (Constant.ZYZJM_SIZE_BETWEEN_300_400.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.between(root.get("mainColSectionSize"), 300, 400));
                        }
                        //主要截面尺寸400-600
                        if (Constant.ZYZJM_SIZE_BETWEEN_400_600.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.between(root.get("mainColSectionSize"), 400, 600));
                        }
                        //主要截面尺寸>=600
                        if (Constant.ZYZJM_SIZE_MORE_600.equals(zyzjmSize)) {
                            predicates.add(criteriaBuilder.ge(root.get("mainColSectionSize"), 600));
                        }
                    }*/
                    //最大柱间距
                    String zdzSpan = analysisQueryVo.getZdzSpan();
                    if (!StringUtils.isEmpty(zdzSpan)) {
                        //最大柱间距<=5
                        if (Constant.ZDZ_SPAN_LESS_5.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.le(root.get("maxColSpace"), 5));
                        }
                        //最大柱间距5-8
                        if (Constant.ZDZ_SPAN_BETWEEN_5_8.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxColSpace"), 5, 8));
                        }
                        //最大柱间距8-10
                        if (Constant.ZDZ_SPAN_BETWEEN_8_10.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxColSpace"), 8, 10));
                        }
                        //最大柱间距>=10
                        if (Constant.ZDZ_SPAN_MORE_10.equals(zdzSpan)) {
                            predicates.add(criteriaBuilder.ge(root.get("maxColSpace"), 10));
                        }
                    }
                    //剪力墙混凝土强度等级
                    String jlqhntqdLevel = analysisQueryVo.getJlqhntqdLevel();
                    if (!StringUtils.isEmpty(jlqhntqdLevel)) {
                        predicates.add(criteriaBuilder.equal(root.get("shearwellConcreteStrengthGrade"), jlqhntqdLevel));
                    }
                    //剪力墙最大间距
                    String jlqzdSpan = analysisQueryVo.getJlqzdSpan();
                    if (!StringUtils.isEmpty(jlqzdSpan)) {
                        //剪力墙最大间距<=30m
                        if (Constant.JLQZD_SPAN_LESS_30.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.le(root.get("maxShearwellSpace"), 30));
                        }
                        //剪力墙最大间距30-40m
                        if (Constant.JLQZD_SPAN_BETWEEN_30_40.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxShearwellSpace"), 30, 40));
                        }
                        //剪力墙最大间距40-50m
                        if (Constant.JLQZD_SPAN_BETWEEN_40_50.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxShearwellSpace"), 40, 50));
                        }
                        //剪力墙最大间距50-60m
                        if (Constant.JLQZD_SPAN_BETWEEN_50_60.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.between(root.get("maxShearwellSpace"), 50, 60));
                        }
                        //剪力墙最大间距>=60m
                        if (Constant.JLQZD_SPAN_MORE_60.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.ge(root.get("maxShearwellSpace"), 60));
                        }
                    }
                    //剪力墙厚度
                    String shearwellThickness = analysisQueryVo.getShearwellThickness();
                    if (!StringUtils.isEmpty(shearwellThickness)) {
                        //剪力墙厚度<=160mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_LESS_160.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.le(root.get("shearwellThickness"), 160));
                        }
                        //剪力墙厚度160mm-200mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_BETWEEN_160_200.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.between(root.get("shearwellThickness"), 160, 200));
                        }
                        //剪力墙厚度200mm-400mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_BETWEEN_200_400.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.between(root.get("shearwellThickness"), 200, 400));
                        }
                        //剪力墙厚度400mm-700mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_BETWEEN_400_700.equals(shearwellThickness)) {
                            predicates.add(criteriaBuilder.between(root.get("shearwellThickness"), 400, 700));
                        }
                        //剪力墙厚度>=700mm
                        if (Constant.HEIGHT_SHEARWELL_THICKNESS_MORE_700.equals(jlqzdSpan)) {
                            predicates.add(criteriaBuilder.ge(root.get("shearwellThickness"), 700));
                        }
                    }
                    //屋盖类别
                    String roofType = analysisQueryVo.getRoofType();
                    if (!StringUtils.isEmpty(roofType)) {
                        predicates.add(criteriaBuilder.equal(root.get("roofType"), roofType));
                    }
                    //楼盖类别
                    String floorType = analysisQueryVo.getFloorType();
                    if (!StringUtils.isEmpty(floorType)) {
                        predicates.add(criteriaBuilder.equal(root.get("floorType"), floorType));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.IS_VALID_YES));
                //审核通过的
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
            }
        };
        List<FwHighStructureEntity> all = highStructureRepository.findAll(querySpecification);
        double count = 0.00;
        for (FwHighStructureEntity highStructureEntity : all) {
            double buildingArea = 0.00;
            if (!PlatformObjectUtils.isEmpty(highStructureEntity.getBuildingArea())) {
                buildingArea = highStructureEntity.getBuildingArea().doubleValue();
                if (!PlatformObjectUtils.isEmpty(highStructureEntity.getFloorNum())) {
                    buildingArea = highStructureEntity.getBuildingArea().doubleValue()
                            * highStructureEntity.getFloorNum().intValue();
                }
            }
            count += buildingArea;
        }
        Double.parseDouble(String.format("%.3f", count));
        return Double.parseDouble(String.format("%.3f", count));
    }

    @Override
    public void export(List<String> idList, HttpServletResponse response) {
        List<FwHighStructureEntity> list = highStructureRepository.findInIdList(idList);
        // 深拷贝
        ArrayList<FwHighStructureVo> vos = new ArrayList<>();
        for (FwHighStructureEntity highStructureEntity : list) {
            if(highStructureEntity.getStatus().equals("1")){
                highStructureEntity.setStatus("未审核");
            }else if(highStructureEntity.getStatus().equals("2")){
                highStructureEntity.setStatus("审核未通过");
            }else if(highStructureEntity.getStatus().equals("3")){
                highStructureEntity.setStatus("审核通过");
            }else if(highStructureEntity.getStatus().equals("4")){
                highStructureEntity.setStatus("省级退回");
            }else {
                highStructureEntity.setStatus("中心退回");
            }
            String detailFile = highStructureEntity.getDetailFile();
            StringBuilder file = new StringBuilder();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(detailFile)){
                //获取数据真实的附件信息
                List<SysAttachmentEntity> byAttachIdsAndIsValid = sysAttachment.findByAttachIdsAndIsValid(Arrays.asList(detailFile.split(",")));
                if(PlatformObjectUtils.isNotEmpty(byAttachIdsAndIsValid)){
                    for (SysAttachmentEntity sysAttachmentEntity : byAttachIdsAndIsValid) {
                        String attachPath = sysAttachmentEntity.getAttachPath();
                        attachPath = attachPath.replace("/","");
                        file.append(attachPath).append(",");
                    }
                }
            }
            if(file.length()>0){
                String fileName = file.substring(0, file.length() - 1);
                highStructureEntity.setDetailFile(fileName);
            }
            FwHighStructureVo vo = new FwHighStructureVo();
            BeanUtils.copyProperties(highStructureEntity, vo);
            vos.add(vo);
        }
        // 导出
        EasyPoiExcelUtil.exportExcel(vos, "高层结构信息统计", "高层结构信息", FwHighStructureVo.class, "高层结构.xls", response);
    }


    @Override
    public long buildingCount(AnalysisQueryVo analysisQueryVo) {
        // 查询条件
        Specification querySpecification = new Specification<FwStructureFormEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwStructureFormEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(analysisQueryVo)) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    // 审批类型
                    String status = analysisQueryVo.getStatus();
                    if (!StringUtils.isEmpty(status)) {
                        if ("审核通过".equals(status)) {
                            // 若为审核通过，查询status状态为3
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                        } else if ("审核不通过".equals(status)) {
                            // 若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_NOT));
                        } else {
                            //若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.DAI_SP));
                        }
                    }else {
                        //默认查询非未提交的
                        //predicates.add(criteriaBuilder.in(root.get("status"), (Constant.DAI_SP,Constant.DAI_SP));
                        CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("status"));
                        in.value(Constant.DAI_SP);
                        in.value(Constant.SP_NOT);
                        in.value(Constant.SP_YES);
                        predicates.add(in);
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.IS_VALID_YES));
                //审核通过的
                //predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                predicates.add(criteriaBuilder.equal(root.get("structureType"), Constant.HIGH_STRUCTURE));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
            }
        };
        return fwStructureFormRepository.count(querySpecification);
    }

    @Override
    public double highAreaCount(AnalysisQueryVo analysisQueryVo) {
        // 查询条件
        Specification querySpecification = new Specification<FwHighStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwHighStructureEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(analysisQueryVo)) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                   //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        predicates.add(criteriaBuilder.equal(root.get("taskName"), taskName));
                    }
                    //抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }
                    // 审批类型
                    String status = analysisQueryVo.getStatus();
                    if (!StringUtils.isEmpty(status)) {
                        if ("审核通过".equals(status)) {
                            // 若为审核通过，查询status状态为3
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                        } else if ("审核不通过".equals(status)) {
                            // 若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_NOT));
                        } else {
                            //若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.DAI_SP));
                        }
                    }else {
                        //默认查询非未提交的
                        //predicates.add(criteriaBuilder.in(root.get("status"), (Constant.DAI_SP,Constant.DAI_SP));
                        CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("status"));
                        in.value(Constant.DAI_SP);
                        in.value(Constant.SP_NOT);
                        in.value(Constant.SP_YES);
                        predicates.add(in);
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.IS_VALID_YES));
                //审核通过的
                //predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
            }
        };
        List<FwHighStructureEntity> all = highStructureRepository.findAll(querySpecification);
        double count = 0.00;
        for (FwHighStructureEntity highStructureEntity : all) {
            double buildingArea = 0.00;
            if (!StringUtils.isEmpty(highStructureEntity.getBuildingArea())) {
                buildingArea = highStructureEntity.getBuildingArea();
            }
            count += buildingArea;
        }
        return count;
    }


}
